package com.utils.http;

import com.entity.Person;
import com.entity.School;
import com.utils.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;

/**
 * http请求工具类
 */
public class HttpUtils {


    /**
     * post请求,发送数据格式为json
     * school、person为测试实体类
     *
     * @return
     */
    public static void postJsonToUrl() {
        try {
            String url = "";
            School school = new School();
            Person person = new Person();
            person.age = 11;
            person.name = "testName";
            school.person = person;

            String entity = JsonUtils.toJson(school);

            HttpClient httpClient = HttpClientBuilder.create().build();

            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(entity);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);
            HttpEntity httpEntity = response.getEntity();

            //若返回数据为json，则用以下方法进行解析，其他方法自行查找
            JSONObject jsonObject = new JSONObject(EntityUtils.toString(httpEntity, "UTF-8"));

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    /**
     * 下载文件
     * @param downloadUrl
     * @param targetPath
     */
    public static Boolean downloadFile(String downloadUrl, String targetPath, String fileType) {
        if (StringUtils.isAnyBlank(downloadUrl, targetPath)) {
            System.out.println("下载参数不正确");
            return false;
        }

        try {

            URL url = new URL(downloadUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");

            //TODO 此选项可设置每次请求的字节数，用于断点续传；例：range:bytes=0-128   range:bytes=129-256  range:bytes=257-
            //connection.setRequestProperty("Range", "bytes=0-100");
            InputStream inputStream = connection.getInputStream();

            String fileName = targetPath + File.separator + Calendar.getInstance().getTimeInMillis() + "." + fileType;
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);

            byte[] b = new byte[1024];
            int nRead;

            while ((nRead = inputStream.read(b, 0, 1024)) > 0) {
                fileOutputStream.write(b, 0, nRead);
            }
            fileOutputStream.close();
            System.out.println(" 下载成功。。文件为" + fileName);
            return true;
        } catch (Exception e) {
            System.out.println("下载失败！" + e.getMessage());
            return false;
        }
    }
}
